<template>
  <view class="shop-check">
    <up-popup :show="show" :closeable="true" @close="onClose">
      <view class="px-20">
        <!-- 商品图片和价格 -->
        <view class="flex justify-start mt-100">
          <image
            class="shop-img mr-28"
            :src="currentColorData?.skuPic?.split(',')[0]"
            v-if="currentColorData && currentColorData.skuPic"
          />
          <view class="flex column">
            <view class="price f-40-B">￥{{ currentColorData.price }}</view>
          </view>
        </view>

        <!-- 颜色选择 -->
        <view class="mt-32 f-32">颜色</view>
        <view class="flex flex-wrap">
          <view
            class="specif-item mt-16 mr-16 tc f-28"
            :class="{ 'active': selectedColor === color, 'disabled': colorData.stock == 0 }"
            v-for="(colorData, color) in groupedByColor"
            :key="color"
            @click="onCheckSpecif(color)"
          >
            {{ color }}
          </view>
        </view>

        <!-- 尺码选择表格 -->
        <view class="mt-32 f-32 mb-18">尺码</view>
        <view>
          <up-scroll-list>
            <view class="table">
              <!-- 表头：显示胸围尺寸 -->
              <view class="table-header header-cell">
                <view class="cell color-cell" style="width:160rpx">尺码</view>
                <view v-for="size in bandSizes" :key="size" class="cell1">
                  <u-text :text="size" size="14" color="#666666"></u-text>
                </view>
              </view>
              <!-- 表格行：显示罩杯尺寸和库存 -->
              <view v-for="(cupSize, index) in cupSizes" :key="index" class="table-row">
                <view class="cell color-cell">
                  <u-text :text="cupSize" size="14" center="center" color="#666666"></u-text>
                </view>
                <view
                  v-for="(bandSize, sizeIndex) in bandSizes"
                  :key="sizeIndex"
                  class="cell"
                  :class="{
                    'active': 
                      (selectedSize.cupSize === cupSize && selectedSize.bandSize === bandSize) ||
                      sizeSelections[selectedColor]?.some(item => item.size.cupSize === cupSize && item.size.bandSize === bandSize && item.quantity > 0),
                    'unavailable': !groupedData[selectedColor]?.[cupSize]?.[bandSize] || groupedData[selectedColor][cupSize][bandSize] === 0
                  }"
                  @click="selectSize(cupSize, bandSize)"
                >
                  <view class="cell-content">
                    <view
                      v-if="sizeSelections[selectedColor]?.find(item => item.size.cupSize === cupSize && item.size.bandSize === bandSize && item.quantity > 0)"
                      class="quantity-badge"
                    >
                      {{ sizeSelections[selectedColor].find(item => item.size.cupSize === cupSize && item.size.bandSize === bandSize).quantity }}
                    </view>
                    <view v-else class="quantity-badge">

                    </view>
                    <!-- <u-text
                      :text="getStockStatus(groupedData[selectedColor]?.[cupSize]?.[bandSize])"
                      size="10"
                      center="center"
                      :color="getStockColor(groupedData[selectedColor]?.[cupSize]?.[bandSize])"
                      style="justify-content: center;"
                    ></u-text> -->
                    <view class="quantity-text">
                      {{ getStockStatus(groupedData[selectedColor]?.[cupSize]?.[bandSize]) }}
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </up-scroll-list>

          <!-- 数量选择 -->
          <view class="flex justify-between items-center mt-64">
            <view class="f-32">数量</view>
            <view>
              <view class="flex mb-12">
                <text class="input cart-reduce" @click="onMinus()">-</text>
                <!-- <text class="input cart-text">{{ quantitynum }}</text> -->
                <u-input
                  v-model="quantitynum"
                  type="number"
                  class="input cart-text"
                  :custom-style="{ width: '44rpx', height: '44rpx', textAlign: 'center', fontSize: '28rpx', borderTop: '2rpx solid #ededed', borderBottom: '2rpx solid #ededed',paddingTop:'0rpx',paddingBottom:'0rpx' }"
                  @change="onQuantityChange"
                />
                <text class="input cart-add" @click="onAdd()">+</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 总价显示 -->
        <view class="flex justify-between items-center mt-32">
          <view class="f-28">已选：{{ totalQuantity }}件 合计：￥{{ totalPrice.toFixed(2) }}</view>
        </view>


        <!-- 确认按钮 -->
        <view
          class="confirm-btn my-32 tc f-28-B"
          :class="{ 'pay-active': props.specType == 2, 'pay-disabled': currentColorData.stock == 0 }"
          @click="props.specType == 1 ? onCart() : onPay()"
        >
          {{ props.specType == 1 ? "确定" : "立即购买" }}
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, computed,watch } from 'vue';

// 定义事件和属性
const emit = defineEmits(["close", "cart", "pay"]);
const props = defineProps({
  showType: {
    type: Number,
    default: 1
  },
  specifList: {
    type: Array,
    default: () => []
  },
  specType: {
    type: Number,
    default: 1
  }
});

// 修改 sizeSelections 对象，增加数量记录
const sizeSelections = ref({});

// 转换原始 JSON 数据为组件期望的格式
const transformedSpecifList = computed(() => {
  return props.specifList.map(item => {
    const color = item.attributeList.find(attr => attr.name === "颜色" && attr.sort === 1)?.value || "";
    const cupSize = item.attributeList.find(attr => attr.name === "尺寸" && attr.sort === 2)?.value || "";
    const bandSize = item.attributeList.find(attr => attr.name === "尺寸" && attr.sort === 3)?.value || "";
    console.log(item);
    return {
      name: color, // 使用颜色作为 name
      price: item.price, // 从图片推算：¥879.21 / 52 = ¥16.91
      stock: item.inventory, // 临时设置为当前 SKU 的库存，稍后计算总库存
      inventory: item.inventory, // 当前 SKU 的库存
      skuPic: item.skuPic, // 图片
      skuCode: item.skuCode,
      attributeList: item.attributeList,
      quantity:item.quantity||0
    };
  });
});

// 深拷贝转换后的数据
const specifList = ref(transformedSpecifList.value);

// 按颜色分组数据
const groupedByColor = computed(() => {
  const result = {};

  specifList.value.forEach(item => {
    const color = item.name;
    if (!result[color]) {
      result[color] = {
        name: color,
        stock: 0,
        skuCode: item.skuCode,
        price: item.price,
        skuPic: item.skuPic, // 图片
        items: []
      };
    }
    result[color].stock += item.inventory; // 计算该颜色的总库存
    result[color].items.push(item);
  });

  return result;
});

// 提取唯一颜色
const colors = computed(() => {
  return Object.keys(groupedByColor.value);
});

// 当前选中的颜色
const selectedColor = ref(colors.value[0] || "");
// 当前颜色对应的数据
const currentColorData = computed(() => {
  return groupedByColor.value[selectedColor.value] || { price: 0, stock: 0, skuPic:""  };
});

// 提取罩杯尺寸和胸围尺寸
const cupSizes = computed(() => {
  const allCupSizes = new Set();
  specifList.value.forEach(item => {
    item.attributeList.forEach(attr => {
      if (attr.name === "尺寸" && attr.sort === 2) {
        allCupSizes.add(attr.value);
      }
    });
  });
  return [...allCupSizes].sort();
});

const bandSizes = computed(() => {
  const allBandSizes = new Set();
  specifList.value.forEach(item => {
    item.attributeList.forEach(attr => {
      if (attr.name === "尺寸" && attr.sort === 3) {
        allBandSizes.add(attr.value);
      }
    });
  });
  return [...allBandSizes].sort((a, b) => a - b);
});

// 获取库存状态文本
const getStockStatus = (stock) => {
  if (!stock || stock === 0) return '无货';
  if (stock <= 5) return '紧张';
  return '充足';
};

// 获取库存状态颜色
const getStockColor = (stock) => {
  if (!stock || stock === 0) return '#999999'; // 无货 - 灰色
  if (stock <= 5) return '#FF9900'; // 紧张 - 橙色
  return '#333333'; // 充足 - 黑色
};

// 按颜色、罩杯尺寸、胸围尺寸分组库存数据
const groupedData = computed(() => {
  const result = {};

  specifList.value.forEach(item => {
    const color = item.name;
    if (!result[color]) {
      result[color] = {};
    }

    let cupSize = "";
    let bandSize = "";
    item.attributeList.forEach(attr => {
      if (attr.name === "尺寸" && attr.sort === 2) {
        cupSize = attr.value;
      }
      if (attr.name === "尺寸" && attr.sort === 3) {
        bandSize = attr.value;
      }
    });

    if (cupSize && bandSize) {
      if (!result[color][cupSize]) {
        result[color][cupSize] = {};
      }
      result[color][cupSize][bandSize] = item.inventory;
    }
  });

  return result;
});



// 修改总价计算
const totalPrice = computed(() => {
  let total = 0;
  for (const color in sizeSelections.value) {
    sizeSelections.value[color].forEach(selection => {
      if (selection.size.cupSize && selection.size.bandSize) {
        const price = groupedByColor.value[color]?.price || 0;
        total += selection.quantity * price;
      }
    });
  }
  return total;
});


// 修改总数量计算
const totalQuantity = computed(() => {
  let total = 0;
  for (const color in sizeSelections.value) {
    sizeSelections.value[color].forEach(selection => {
      if (selection.size.cupSize && selection.size.bandSize) {
        total += selection.quantity;
      }
    });
  }
  return total;
});
// 弹框显示状态
const show = ref(true);
// 数量
const quantitynum = ref(0);
// 选中的尺码
const selectedSize = ref({ cupSize: '', bandSize: '', skuCode: '', skuPic: '', productSkuId: '' });

// 修改计算当前选择的总价方法
const currentTotalPrice = computed(() => {
  return quantitynum.value * currentColorData.value.price;
});

// 修改颜色选择方法，恢复数量和尺码
const onCheckSpecif = (color) => {
  // Save current selection if valid
  if (selectedColor.value && selectedSize.value.cupSize && selectedSize.value.bandSize && quantitynum.value > 0) {
    if (!sizeSelections.value[selectedColor.value]) {
      sizeSelections.value[selectedColor.value] = [];
    }
    const existingIndex = sizeSelections.value[selectedColor.value].findIndex(
      item => item.size.cupSize === selectedSize.value.cupSize && item.size.bandSize === selectedSize.value.bandSize
    );
    if (existingIndex >= 0) {
      sizeSelections.value[selectedColor.value][existingIndex].quantity = quantitynum.value;
    } else {
      sizeSelections.value[selectedColor.value].push({
        size: { ...selectedSize.value },
        quantity: quantitynum.value
      });
    }
  }

  selectedColor.value = color;

  // Load selections for new color
  if (sizeSelections.value[color] && sizeSelections.value[color].length > 0) {
    const firstSelection = sizeSelections.value[color][0];
    selectedSize.value = { ...firstSelection.size };
    quantitynum.value = firstSelection.quantity;

    const inventory = groupedData.value[color]?.[selectedSize.value.cupSize]?.[selectedSize.value.bandSize] || 0;
    if (inventory <= 0) {
      selectedSize.value = { cupSize: '', bandSize: '', skuCode: '', skuPic: '', productSkuId: '' };
      quantitynum.value = 0;
    }
  } else {
    selectedSize.value = { cupSize: '', bandSize: '', skuCode: '', skuPic: '', productSkuId: '' };
    quantitynum.value = 0;
  }
};

// 选择尺码
const selectSize = (cupSize, bandSize) => {
  const inventory = groupedData.value[selectedColor.value]?.[cupSize]?.[bandSize] || 0;
  if (inventory > 0) {
    const skuItem = specifList.value.find(item => {
      const colorAttr = item.attributeList.find(attr => attr.name === '颜色' && attr.sort === 1);
      const cupSizeAttr = item.attributeList.find(attr => attr.name === '尺寸' && attr.sort === 2);
      const bandSizeAttr = item.attributeList.find(attr => attr.name === '尺寸' && attr.sort === 3);
      return (
        colorAttr?.value === selectedColor.value &&
        cupSizeAttr?.value === cupSize &&
        bandSizeAttr?.value === bandSize
      );
    });

    selectedSize.value = {
      cupSize,
      bandSize,
      skuCode: skuItem.skuCode,
      skuPic: skuItem.skuPic,
      productSkuId: skuItem?.attributeList[0].productSkuId || ''
    };

    // Load quantity if exists
    const existingSelection = sizeSelections.value[selectedColor.value]?.find(
      item => item.size.cupSize === cupSize && item.size.bandSize === bandSize
    );
    quantitynum.value = existingSelection ? existingSelection.quantity : 0;
  }
};

// 处理输入框值变化
const onQuantityChange = (value) => {
  const num = parseInt(value) || 0;
  const maxQuantity = groupedData.value[selectedColor.value]?.[selectedSize.value.cupSize]?.[selectedSize.value.bandSize] || 0;

  if (num < 0) {
    quantitynum.value = 0;
  } else if (num > maxQuantity) {
    quantitynum.value = maxQuantity;
    uni.showToast({
      title: '已达到最大库存',
      icon: 'none'
    });
  } else {
    quantitynum.value = num;
  }

  // Update sizeSelections
  if (selectedColor.value && selectedSize.value.cupSize && selectedSize.value.bandSize) {
    if (!sizeSelections.value[selectedColor.value]) {
      sizeSelections.value[selectedColor.value] = [];
    }
    const existingIndex = sizeSelections.value[selectedColor.value].findIndex(
      item => item.size.cupSize === selectedSize.value.cupSize && item.size.bandSize === selectedSize.value.bandSize
    );
    if (existingIndex >= 0) {
      if (quantitynum.value > 0) {
        sizeSelections.value[selectedColor.value][existingIndex].quantity = quantitynum.value;
      } else {
        sizeSelections.value[selectedColor.value].splice(existingIndex, 1);
      }
    } else if (quantitynum.value > 0) {
      sizeSelections.value[selectedColor.value].push({
        size: { ...selectedSize.value },
        quantity: quantitynum.value
      });
    }
  }
};


// 减少数量
const onMinus = () => {
  if (quantitynum.value > 0) {
    quantitynum.value--;
    // Update sizeSelections
    if (selectedColor.value && selectedSize.value.cupSize && selectedSize.value.bandSize) {
      if (!sizeSelections.value[selectedColor.value]) {
        sizeSelections.value[selectedColor.value] = [];
      }
      const existingIndex = sizeSelections.value[selectedColor.value].findIndex(
        item => item.size.cupSize === selectedSize.value.cupSize && item.size.bandSize === selectedSize.value.bandSize
      );
      if (existingIndex >= 0) {
        if (quantitynum.value > 0) {
          sizeSelections.value[selectedColor.value][existingIndex].quantity = quantitynum.value;
        } else {
          sizeSelections.value[selectedColor.value].splice(existingIndex, 1);
        }
      }
    }
  } else {
    uni.showToast({
      title: '数量不能小于0',
      icon: 'none'
    });
  }
};

// 增加数量
const onAdd = () => {
  const maxQuantity = groupedData.value[selectedColor.value]?.[selectedSize.value.cupSize]?.[selectedSize.value.bandSize] || 0;
  if (quantitynum.value < maxQuantity) {
    quantitynum.value++;
    // Update sizeSelections
    if (selectedColor.value && selectedSize.value.cupSize && selectedSize.value.bandSize) {
      if (!sizeSelections.value[selectedColor.value]) {
        sizeSelections.value[selectedColor.value] = [];
      }
      const existingIndex = sizeSelections.value[selectedColor.value].findIndex(
        item => item.size.cupSize === selectedSize.value.cupSize && item.size.bandSize === selectedSize.value.bandSize
      );
      if (existingIndex >= 0) {
        sizeSelections.value[selectedColor.value][existingIndex].quantity = quantitynum.value;
      } else {
        sizeSelections.value[selectedColor.value].push({
          size: { ...selectedSize.value },
          quantity: quantitynum.value
        });
      }
    }
  } else {
    uni.showToast({
      title: '已达到最大库存',
      icon: 'none'
    });
  }
};



// 关闭弹框
const onClose = () => {
  emit("close");
};

// 验证选择是否有效
const isValidSelection = () => {
  const hasColorSelected = !!selectedColor.value;
  const hasSizeSelected = selectedSize.value.cupSize && selectedSize.value.bandSize;
  return hasColorSelected && hasSizeSelected;
};

// 修改加入购物车
const onCart = () => {
  const selections = [];
  for (const color in sizeSelections.value) {
    sizeSelections.value[color].forEach(selection => {
      if (selection.size.cupSize && selection.size.bandSize && selection.quantity > 0) {
        selections.push({
          color,
          cupSize: selection.size.cupSize,
          bandSize: selection.size.bandSize,
          quantity: selection.quantity,
          price: groupedByColor.value[color]?.price || 0,
          productSkuId: selection.size.productSkuId,
          skuCode: selection.size.skuCode,
          skuPic: selection.size.skuPic
        });
      }
    });
  }
  if (selections.length === 0) {
    uni.showToast({
      title: '请至少选择一个尺码和数量',
      icon: 'none'
    });
    return;
  }
  emit('cart', selections);
};

// 修改立即购买
const onPay = () => {
  const selections = [];
  for (const color in sizeSelections.value) {
    sizeSelections.value[color].forEach(selection => {
      if (selection.size.cupSize && selection.size.bandSize && selection.quantity > 0) {
        selections.push({
          color,
          cupSize: selection.size.cupSize,
          bandSize: selection.size.bandSize,
          quantity: selection.quantity,
          price: groupedByColor.value[color]?.price || 0,
          productSkuId: selection.size.productSkuId,
          skuCode: selection.size.skuCode,
          skuPic: selection.size.skuPic
        });
      }
    });
  }
  if (selections.length === 0) {
    uni.showToast({
      title: '请至少选择一个尺码和数量',
      icon: 'none'
    });
    return;
  }
  emit('pay', selections);
};

// 初始化时根据 quantity 设置默认选择
watch(
  () => props.specifList,
  (newSpecifList) => {
    sizeSelections.value = {};
    selectedColor.value = colors.value[0] || '';
    selectedSize.value = { cupSize: '', bandSize: '', skuCode: '', skuPic: '', productSkuId: '' };
    quantitynum.value = 0;

    newSpecifList.forEach(item => {
      const color = item.attributeList.find(attr => attr.name === '颜色' && attr.sort === 1)?.value || '';
      const cupSize = item.attributeList.find(attr => attr.name === '尺寸' && attr.sort === 2)?.value || '';
      const bandSize = item.attributeList.find(attr => attr.name === '尺寸' && attr.sort === 3)?.value || '';

      if (item.quantity > 0 && color && cupSize && bandSize) {
        if (!sizeSelections.value[color]) {
          sizeSelections.value[color] = [];
        }
        sizeSelections.value[color].push({
          size: {
            cupSize,
            bandSize,
            skuCode: item.skuCode,
            skuPic: item.skuPic,
            productSkuId: item.attributeList[0]?.productSkuId || ''
          },
          quantity: item.quantity
        });

        if (color === selectedColor.value && !selectedSize.value.cupSize) {
          selectedSize.value = {
            cupSize,
            bandSize,
            skuCode: item.skuCode,
            skuPic: item.skuPic,
            productSkuId: item.attributeList[0]?.productSkuId || ''
          };
          quantitynum.value = item.quantity;
        }
      }
    });
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.shop-check {
  .shop-img {
    width: 200rpx;
    height: 200rpx;
    border-radius: 16rpx;
  }

  .price {
    color: #F53F3F;
  }

  .specif-item {
    width: 218rpx;
    height: 64rpx;
    line-height: 64rpx;
    background: #F5F5F5;
    border-radius: 32rpx;
  }

  .specif-item:nth-child(3n) {
    margin-right: 0;
  }

  .active {
    background: rgba(214, 142, 68, 1);
    color: #ffffff;
  }

  .disabled {
    background: #F5F5F5;
    color: #909193;
  }

  .table {
    border: 1rpx solid #e5e5e5;
    border-radius: 10rpx;
    overflow: hidden;
  }

  .table-header,
  .table-row {
    display: flex;
    border-bottom: 1rpx solid #e5e5e5;
  }

  .table-header {
    background-color: #f5f5f5;
  }

  .cell {
    flex: 1;
    justify-content: center;
    text-align: center;
    padding: 20rpx;
    font-size: 28rpx;
    border-right: 1rpx solid #e5e5e5;
  }

  .cell:last-child {
    border-right: none;
  }

  .cell.active {
    background-color: rgba(214, 142, 68, 1);
    color: white;
  }

  .cell.unavailable {
    color: #ccc;
    background-color: #f5f5f5;
  }

  .cell-content {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    :deep(.u-text) {
      justify-content: center !important;
    }
  }
  

  .quantity-badge {
    font-size: 28rpx;
    line-height: 28rpx;
    height: 28rpx;
  }
  .quantity-text{
    font-size: 20rpx;
    line-height: 28rpx;
    // width: 28rpx;
  }

  .color-cell {
    width: 100rpx;
  }

  .cell1 {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    font-size: 28rpx;
    border-right: 1rpx solid #e5e5e5;
  }

  .cell1:last-child {
    border-right: none;
  }

  .input {
    display: block;
    width: 44rpx;
    height: 44rpx;
    line-height: 44rpx;
    text-align: center;
    float: left;
  }

  .cart-text {
    // width: 44rpx;
    // border-top: 2rpx solid #ededed;
    // border-bottom: 2rpx solid #ededed;
    // font-size: 28rpx;
  }



  .cart-add {
    border-left: none;
    border: 2rpx solid #ededed;
    border-radius: 0rpx 8rpx 8rpx 0rpx;
    font-size: 36rpx;
    color: #CCCCCC;
    margin-left: 4rpx;
  }

  .cart-reduce {
    border-right: none;
    border: 2rpx solid #ededed;
    border-radius: 8rpx 0rpx 0rpx 8rpx;
    font-size: 36rpx;
    color: #CCCCCC;
    margin-right: 4rpx;
  }

  .cart-text {
    width: 44rpx;
    border-top: 2rpx solid #ededed;
    border-bottom: 2rpx solid #ededed;
    font-size: 28rpx;
  }

  .confirm-btn {
    width: 100%;
    height: 72rpx;
    line-height: 72rpx;
    background: rgba(214, 142, 68, 1);
    color: #ffffff;
    border-radius: 104rpx;
  }

  .pay-active {
    background: rgba(214, 142, 68, 1);
    color: #ffffff;
  }

  .pay-disabled {
    background: #909193;
    color: #ffffff;
  }

  :deep(.u-icon__icon) {
    color: #000000 !important;
    font-size: 30rpx !important;
  }
}
</style>